package org.vates.practicofinal.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.vates.practicofinal.dao.hibernate.UserDao;
import org.vates.practicofinal.dao.model.User;
import org.vates.practicofinal.dao.model.UserRole;
import org.vates.practicofinal.service.SecurityService;
import org.vates.practicofinal.service.impl.security.CustomUserDetails;
import org.vates.practicofinal.service.impl.security.UserGrantedAuthority;

@Component("securityService")
public class SecurityServiceImpl implements SecurityService {

	@Autowired
	private UserDao userDao;
	
	@Autowired
	@Qualifier("authenticationManager")
	private AuthenticationManager authenticationManager;
	
	@Override
	@Transactional
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
        if (username != null && !username.equals("")) {
            User user = userDao.getUserByName(username);
            if (user == null) {
                return null;
            }
            Iterator<UserRole> it = user.getUserRoles().iterator();
            List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
            while (it.hasNext()) {
            	String authority = it.next().getAuthority();
            	GrantedAuthority grantedAuth = new UserGrantedAuthority(authority);
            	grantedAuthorities.add(grantedAuth);
            }
            
            CustomUserDetails cu = new CustomUserDetails(user.getId(), user.getUserName(), user.getPassword(),
                                           grantedAuthorities.toArray(new GrantedAuthority[]{}), user.getEnabled());
            return cu;
        } else {
            return null;
        }

	}

	@Override
	public boolean login(String userName, String password) {
		try {
			Authentication authenticate = authenticationManager
					.authenticate(new UsernamePasswordAuthenticationToken(
							userName, password));
			if (authenticate.isAuthenticated()) {
				SecurityContextHolder.getContext().setAuthentication(
						authenticate);				
				return true;
			}
		} catch (AuthenticationException e) {			
		}
		return false;
	}

}
